import { bridgeProxy } from './bridge';
import { buildGatewayUrl } from './config';

type HttpMethod = 'GET' | 'POST';

function getToken(): string {
  try {
    const token = localStorage.getItem('token') || '';
    return token.startsWith('Bearer ') ? token : (token ? `Bearer ${token}` : '');
  } catch {
    return '';
  }
}

export async function request<T = any>(
  pathOrUrl: string,
  options: { method?: HttpMethod; params?: any; data?: any; headers?: Record<string, string> } = {}
): Promise<T> {
  const method = (options.method || 'GET').toUpperCase() as HttpMethod;
  const url = buildGatewayUrl(pathOrUrl);
  // const timestamp = Date.now();
  const bearer = getToken();
  // const privateKey = bearer.replace('Bearer ', '');

  const headers: Record<string, string> = {
    Accept: '*/*',
    ...(options.headers || {}),
  };

  // Authorization
  if (bearer) headers['Authorization'] = bearer;

  // Sign & Timestamp
  // const signParams = method === 'GET' ? options.params : options.data;
  // const sign = generateSign(signParams, timestamp, method.toLowerCase() as any, `Bearer ${privateKey}`);
  // headers['Sign'] = sign;
  // headers['Timestamp'] = String(timestamp);
  headers['X-Request-Auth'] = "UserId/AES";

  const body = method === 'GET' ? undefined : options.data;
  const query = method === 'GET' && options.params ? `?${new URLSearchParams(options.params).toString()}` : '';

  return bridgeProxy<T>({ url: `${url}${query}`, method, headers, body });
}


